package com.example.administrator.exkotlin.net

import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.*
import java.io.IOException
import java.lang.StringBuilder

/**
 * Author by lp,on 2020/8/27/027,10:40.
 */
class OkHttpIml : IHttpRqust {
    override fun <T> excute(istener: IHttpRqust.URlListener?, request: T) {
        //创建要给okhttp实例
        val client = OkHttpClient()
        //创建要给请求对象
        val request = Request.Builder().url(request as String).build()
        //发送请求,并接收返回(同步的方式execute())
//        val response=client.newCall(request).execute()

        val call = client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                istener?.response("请求失败")
            }

            override fun onResponse(call: Call, response: Response) {
                val result = response.body?.string()
                val mResponseData = Gson().fromJson<ResponseData>(result, object : TypeToken<ResponseData>() {}.type)
                Log.i("OkHttpIml", result)
                Log.i("OkHttpIml", mResponseData.toString())
                istener?.response(mResponseData.toString())
            }

        })
    }


}